<template>
  <div class="order-list">
    <div v-if="orders.length === 0" class="empty-orders">
      <el-empty description="暂无订单" />
    </div>
    <div v-else class="order-items">
      <div v-for="order in orders" :key="order.id" class="order-item" @click="goToOrderDetail(order.id)">
        <div class="order-header">
          <div class="order-header-left">
          <span class="order-no">订单号: {{ order.orderNo }}</span>
            <span class="order-time">{{ formatDate(order.createdAt) }}</span>
          </div>
          <el-tag class="order-status-tag" :type="getStatusType(order.status)" size="small" effect="dark">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>
        <div class="order-content">
          <div class="product-info">
            <div class="image-container">
              <img :src="order.productImageUrl || 'https://via.placeholder.com/80'" alt="商品图片" class="product-image" />
            </div>
            <div class="product-details">
              <h3 class="product-name">{{ order.productName || '商品信息不可用' }}</h3>
              <div class="price-and-seller">
                <p class="product-price">¥{{ order.price?.toFixed(2) || '0.00' }}</p>
                <div class="seller-info" v-if="order.sellerName">
                  <el-avatar :size="24" :src="getSellerAvatar(order.sellerAvatar)"></el-avatar>
                  <span class="seller-name">{{ order.sellerName }}</span>
                </div>
              </div>
              <div class="order-extra-info" v-if="order.paymentMethod || order.transactionLocation">
                <span v-if="order.paymentMethod" class="payment-method">
                  <el-icon><CreditCard /></el-icon>{{ order.paymentMethod }}
                </span>
                <span v-if="order.transactionLocation" class="transaction-location">
                  <el-icon><Location /></el-icon>{{ order.transactionLocation }}
                </span>
              </div>
              <div class="order-remark" v-if="order.remark">
                <span class="remark-label">备注: </span>
                <span class="remark-content">{{ order.remark }}</span>
              </div>
              
              <!-- 买家评价 -->
              <div class="review-section" v-if="order.status === 2 || order.status === 4">
                <div class="review-title">买家评价</div>
                <div v-if="order.buyerReview && order.buyerReview.content" class="review-content">
                  <div class="review-rating">
                    <el-rate 
                      v-model="order.buyerReview.ratingScore" 
                      disabled 
                      show-score 
                      text-color="#ff9900"
                      score-template="{value}分"
                    ></el-rate>
                  </div>
                  <div class="review-text">{{ order.buyerReview.content }}</div>
                  <div class="review-time" v-if="order.buyerReview.createdAt">
                    {{ formatDate(order.buyerReview.createdAt) }}
                  </div>
                </div>
                <div v-else class="no-review">
                  <span class="no-review-text">暂未评价</span>
                </div>
              </div>
              
              <!-- 卖家评价 -->
              <div class="review-section" v-if="order.status === 2 || order.status === 4">
                <div class="review-title">卖家评价</div>
                <div v-if="order.sellerReview && order.sellerReview.content" class="review-content">
                  <div class="review-rating">
                    <el-rate 
                      v-model="order.sellerReview.ratingScore" 
                      disabled 
                      show-score 
                      text-color="#ff9900"
                      score-template="{value}分"
                    ></el-rate>
                  </div>
                  <div class="review-text">{{ order.sellerReview.content }}</div>
                  <div class="review-time" v-if="order.sellerReview.createdAt">
                    {{ formatDate(order.sellerReview.createdAt) }}
                  </div>
                </div>
                <div v-else class="no-review">
                  <span class="no-review-text">暂未评价</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="order-footer">
          <span class="total-amount">实付款: <span class="amount">¥{{ order.price?.toFixed(2) || '0.00' }}</span></span>
          <div class="action-buttons">
            <el-button 
            v-if="order.status === 1" 
              type="primary"
              size="small"
            @click.stop="handleConfirmReceipt(order.id)"
          >
              确认交易完成
            </el-button>
            <el-button
              v-if="order.status === 4 && !order.isReviewed"
              type="success"
              size="small"
            @click.stop="handleReview(order.id)"
          >
            评价订单
            </el-button>
            <el-button
            v-if="order.status === 1"
              type="info"
              size="small"
              plain
            @click.stop="handleCancel(order.id)"
          >
            取消订单
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 取消订单对话框 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消订单"
      width="30%"
      destroy-on-close
    >
      <el-form :model="cancelForm" label-width="80px">
        <el-form-item label="取消原因">
          <el-select v-model="cancelForm.reason" placeholder="请选择取消原因" style="width: 100%">
            <el-option label="我不想要了" value="不想要了" />
            <el-option label="信息填写错误" value="信息填写错误" />
            <el-option label="与卖家协商一致" value="协商一致" />
            <el-option label="其他原因" value="其他原因" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="cancelForm.reason === '其他原因'" label="详细原因">
          <el-input v-model="cancelForm.detail" type="textarea" rows="3" placeholder="请填写详细原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel" :loading="cancelLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 评价订单对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="评价订单"
      width="40%"
      destroy-on-close
    >
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
        <el-form-item label="商品评分" prop="ratingScore">
          <el-rate v-model="reviewForm.ratingScore" :texts="['很差', '较差', '一般', '满意', '很满意']" show-text></el-rate>
        </el-form-item>
        <el-form-item label="卖家信誉评分" prop="creditScore">
          <el-rate v-model="reviewForm.creditScore" :texts="['很差', '较差', '一般', '满意', '很满意']" show-text></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="reviewForm.content" type="textarea" rows="4" placeholder="请输入您的评价内容"></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :limit="3"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReview" :loading="reviewLoading">
            提交评价
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useOrderStore } from '@/stores/order';
import { Location, CreditCard } from '@element-plus/icons-vue';

// 定义Order接口
interface Order {
  id: number;
  orderNo: string;
  createdAt: any; // 修改为any类型，因为可能是字符串或数组
  status: number;
  price: number;
  isReviewed?: boolean;
  // 新增字段
  productName?: string;
  productImageUrl?: string;
  sellerName?: string;
  sellerAvatar?: string;
  remark?: string; // 添加备注字段
  paymentMethod?: string; // 添加支付方式
  transactionLocation?: string; // 添加交易地点
  // 评价相关字段
  buyerReview?: {
    content?: string;
    ratingScore?: number;
    creditScore?: number;
    images?: string;
    createdAt?: any;
  };
  sellerReview?: {
    content?: string;
    ratingScore?: number;
    creditScore?: number;
    images?: string;
    createdAt?: any;
  };
}

const props = defineProps({
  orders: {
    type: Array as () => Order[],
    default: () => []
  }
});

const emit = defineEmits(['refresh']);
const router = useRouter();
const orderStore = useOrderStore();

// 订单取消相关
const cancelDialogVisible = ref(false);
const cancelLoading = ref(false);
const currentOrderId = ref<number | null>(null);
const cancelForm = ref({
  reason: '不想要了',
  detail: ''
});

// 订单评价相关
const reviewDialogVisible = ref(false);
const reviewLoading = ref(false);
const reviewFormRef = ref<any>(null);
const uploadedImages = ref<string[]>([]);
const reviewForm = ref({
  ratingScore: 5,
  creditScore: 5,
  content: '',
  images: ''
});

const reviewRules = {
  ratingScore: [{ required: true, message: '请给商品评分', trigger: 'change' }],
  creditScore: [{ required: true, message: '请给卖家信誉评分', trigger: 'change' }],
  content: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
};

// 格式化日期
const formatDate = (dateValue: any) => {
  if (!dateValue) return '';
  
  // 处理数组格式的时间 [year, month, day, hour, minute, second]
  if (Array.isArray(dateValue)) {
    const [year, month, day, hour, minute] = dateValue;
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  }
  
  // 处理字符串格式
  if (typeof dateValue === 'string') {
    const date = new Date(dateValue);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
  
  return '';
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '待交易',
    2: '已完成',
    3: '已取消',
    4: '待评价'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态对应的标签类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'warning'
  };
  return typeMap[status] || '';
};

// 跳转到订单详情页
const goToOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`);
};

// 确认收货
const handleConfirmReceipt = async (orderId: number) => {
  try {
    await ElMessageBox.confirm(
    '确认交易已完成吗？',
    '确认交易',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
    );
    
    const result = await orderStore.confirmReceipt(orderId);
    if (result) {
        ElMessage.success('交易已确认完成，请及时评价');
      emit('refresh');
      } else {
        ElMessage.error('确认交易失败');
      }
    } catch (error) {
    if (error !== 'cancel') {
      console.error('确认交易失败:', error);
      ElMessage.error('确认交易失败');
    }
  }
};

// 取消订单
const handleCancel = (orderId: number) => {
  currentOrderId.value = orderId;
  cancelForm.value = { reason: '不想要了', detail: '' };
  cancelDialogVisible.value = true;
};

// 确认取消订单
const confirmCancel = async () => {
  if (!currentOrderId.value) return;
  
  cancelLoading.value = true;
  try {
    const reason = cancelForm.value.reason === '其他原因' 
      ? cancelForm.value.detail 
      : cancelForm.value.reason;
      
    const result = await orderStore.cancelOrder(currentOrderId.value, reason);
    if (result) {
      ElMessage.success('订单已取消');
      cancelDialogVisible.value = false;
      emit('refresh');
    } else {
      ElMessage.error('取消订单失败');
    }
  } catch (error) {
    console.error('取消订单失败:', error);
    ElMessage.error('取消订单失败');
  } finally {
    cancelLoading.value = false;
  }
};

// 评价订单
const handleReview = (orderId: number) => {
  currentOrderId.value = orderId;
  reviewForm.value = {
    ratingScore: 5,
    creditScore: 5,
    content: '',
    images: ''
  };
  uploadedImages.value = [];
  reviewDialogVisible.value = true;
};

// 上传图片成功回调
const handleUploadSuccess = (response: any) => {
  uploadedImages.value.push(response.data.url);
};

// 移除上传图片
const handleUploadRemove = (file: any) => {
  const url = file.response?.data?.url;
  if (url) {
    const index = uploadedImages.value.indexOf(url);
    if (index !== -1) {
      uploadedImages.value.splice(index, 1);
    }
  }
};

// 提交评价
const submitReview = async () => {
  if (!reviewFormRef.value || !currentOrderId.value) return;
  
  try {
    await reviewFormRef.value.validate();
    
    reviewLoading.value = true;
    
    // 组合图片URL
    reviewForm.value.images = uploadedImages.value.join(',');
    
    const result = await orderStore.createOrderReview(currentOrderId.value, reviewForm.value);
    if (result) {
      ElMessage.success('评价提交成功');
      reviewDialogVisible.value = false;
      emit('refresh');
    } else {
      ElMessage.error('提交评价失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交评价失败:', error);
      ElMessage.error('提交评价失败');
    }
  } finally {
    reviewLoading.value = false;
  }
};

// 获取卖家头像URL
const getSellerAvatar = (avatar: string | undefined) => {
  if (!avatar) return 'https://via.placeholder.com/24';
  
  // 如果已经是完整URL，则直接返回
  if (avatar.startsWith('http')) return avatar;
  
  // 否则拼接图片路径
  return `/images/user/${avatar}`;
};
</script>

<style scoped>
.order-list {
  width: 100%;
}

.empty-orders {
  margin: 30px 0;
}

.order-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #ebeef5;
}

.order-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  background-color: #f9fafc;
  border-bottom: 1px solid #ebeef5;
}

.order-header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.order-no {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.order-time {
  color: #909399;
  font-size: 13px;
}

.order-status-tag {
  font-weight: 500;
  letter-spacing: 0.5px;
}

.order-content {
  padding: 16px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.image-container {
  flex-shrink: 0;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #f0f0f0;
  width: 80px;
  height: 80px;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 80px;
}

.product-name {
  margin: 0 0 12px;
  font-size: 16px;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price-and-seller {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  color: #FF6B35;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.seller-info {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: #f9f9f9;
  padding: 4px 10px;
  border-radius: 100px;
}

.seller-name {
  color: #606266;
  font-size: 13px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fafafa;
  border-top: 1px solid #ebeef5;
}

.total-amount {
  color: #606266;
  font-size: 14px;
}

.amount {
  color: #FF6B35;
  font-weight: 600;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.order-extra-info {
  display: flex;
  margin-top: 8px;
  gap: 16px;
  font-size: 13px;
  color: #606266;
}

.payment-method, .transaction-location {
  display: flex;
  align-items: center;
  gap: 4px;
}

.order-remark {
  margin-top: 8px;
  font-size: 13px;
  color: #606266;
  background-color: #f9f9f9;
  padding: 4px 8px;
  border-radius: 4px;
  border-left: 2px solid #E6A23C;
}

.remark-label {
  font-weight: 500;
}

.remark-content {
  word-break: break-all;
}

.review-section {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px dashed #e0e0e0;
}

.review-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.review-content {
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.review-rating {
  margin-bottom: 6px;
}

.review-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
  word-break: break-word;
}

.review-time {
  font-size: 12px;
  color: #909399;
  margin-top: 6px;
  text-align: right;
}

.no-review {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  text-align: center;
}

.no-review-text {
  font-size: 13px;
  color: #909399;
}
</style> 